<?php
/**
 * Created by PhpStorm.
 * User: junyv
 * Date: 2016/9/21
 * Time: 17:19
 */

namespace app\manage\controller;


class Setting extends Base
{
    private $mod;
    public function _initialize() {
        parent::_initialize();
        $this->mod = model('setting');
    }
    public function index(){
        $type = input('param.type','site');
        if($info = $this->getInfo($type)){
            $this->assign('info',$info['data']);
            $this->assign('base',$info);
            $template = $type.'_edit';
        }else{
            $template = $type.'_add';
        }
        if($type == 'weixin'){
            //$weixin_url = str_replace('admin.','weixin.',request()->host());
            $this->assign('auth_url','http://'.config('domain.mobile').'/weixin/index.html');
        }
        $this->assign('action_name',$type);
        return $this->fetch($template);
    }
    //空操作
    public function _empty($action){
        $this->redirect('index',['type'=>$action,'menuid'=>$this->menuid]);
    }
    private function getInfo($name){
        //$name = $this->action_name;
        $map['name'] = $name;
        $info = $this->mod->where($map)->find();
        return $info;
    }

    /**
     * 更新站点设置缓存
     */
    public function cache(){
        if($this->doCache()){
            $this->success('站点设置缓存更新完成','index');
        }else{
            $this->error('暂无可缓存数据','index');
        }
    }
    public function doCache(){
        $lists = $this->mod->select();
        if($lists){
            foreach($lists as $v){
                cache($v['name'],$v['data']);
            }
            return true;
        }
        return false;
    }
    //后置事件 生成缓存文件
    public function addDo(){
        \app\manage\model\Setting::event('after_insert',function($obj){
            cache($obj->name,$obj->data);
            return true;
        });
        parent::addDo();
    }
    //后置事件 生成缓存文件
    public function editDo(){
        \app\manage\model\Setting::event('after_update',function($obj){
            cache($obj->name,$obj->data);
            return true;
        });
        parent::editDo();
    }
    public function ajaxUploadFile(){
        $files = '';
        if(isset($_FILES['file']) && !empty($_FILES['file']['name'])){
            $file = request()->file('file');
            // 移动到框架应用根目录/public/uploads/ 目录下
            $info = $file->move(ROOT_PATH.'/public/','');
            if($info){
                $files = str_replace('\\','/',$info->getSaveName());
            }else{
                // 上传失败获取错误信息
                request()->isAjax() ? $this->ajaxReturn(0,$file->getError()) : $this->error($file->getError());
            }
        }
        if($files){
            $this->ajaxReturn(1,'上传成功',$files);
        }else{
            $this->ajaxReturn(0,'请选择文件');
        }
    }
}